package com.whzykj.ctrl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletInputStream;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.whzykj.common.CommonUtils;
import com.whzykj.common.DateUtil;
import com.whzykj.common.DbUtil;
import com.whzykj.common.DictCache;
import com.whzykj.common.JsonUtil;
import com.whzykj.model.Dictionary;
import com.whzykj.model.GoodsInfo;
import com.whzykj.model.Price;
import com.whzykj.model.Station;
import com.whzykj.model.Store;
import com.whzykj.model.Userinfo;

public class GoodsController extends Controller {

	public void index() {
		this.renderJsp("/admin/system/goodslist.jsp");
	}

	public void saleindex() {
		this.renderJsp("/admin/system/salegoodslist.jsp");
	}

	public void saleoff() {
		this.renderJsp("/admin/system/salegoodsoff.jsp");
	}

	public void readyForPutAway() {
		this.renderJsp("/admin/system/readyForPutAwayGoods.jsp");
	}

	/*
	 * 列表显示所有菜品信息
	 */
	public void goodslist() {
		Integer page = this.getParaToInt("page");
		Integer rows = this.getParaToInt("rows");

//		String sqlBefore = " SELECT g.*,c.store_num,b.SALE_PRICE,b.UNIT_PRICE,c.sale_num,c.limit_num  ";
//		StringBuffer sqlAfter = new StringBuffer(
//				" FROM goodsinfo g,PRICE b,store c where g.goods_status=1 and g.GOODS_ID=c.GOODS_ID AND g.GOODS_ID=b.GOODS_ID  ");
//		sqlAfter.append(" and date(b.set_date) = curdate() and date(c.set_date) = curdate()  ");
//		sqlAfter.append("  and b.station_id=-1 ");
//		sqlAfter.append("  ORDER BY g.create_time DESC ");
		
		
		StringBuffer sqlBefore=new StringBuffer("SELECT gi.goods_id,gi.goods_name,gi.app_name,gi.goods_kind,dic.dict_name,gi.goods_spec,");
		sqlBefore.append("(select sale_price from price where goods_id=gi.goods_id order by set_date desc LIMIT 1) as sale_price,");
		sqlBefore.append("(select UNIT_PRICE from price where goods_id=gi.goods_id order by set_date desc LIMIT 1) as unit_price,");
		sqlBefore.append("(select SUM(sale_num) from store where goods_id=gi.goods_id order by set_date desc) as sale_num,");
		sqlBefore.append("(select store_num from store where goods_id=gi.goods_id order by set_date DESC LIMIT 1) as store_num,");
		sqlBefore.append("(select limit_num from store where goods_id=gi.goods_id order by set_date DESC LIMIT 1) as limit_num");
		String sqlAfter="FROM goodsinfo gi inner join dictionary dic on dic.dict_code=gi.goods_kind where gi.GOODS_STATUS=1 ORDER BY GOODS_ID";
		Page<GoodsInfo> paginate = GoodsInfo.me.paginate(page, rows, sqlBefore.toString(),sqlAfter);
		List<GoodsInfo> orderlist = paginate.getList();
//		if (orderlist != null && orderlist.size() > 0) {
//			for (GoodsInfo orderInfo : orderlist) {
//				String goods_kind = orderInfo.getStr("goods_kind");
//				String goods_kindname = DictCache.cache
//						.getDicByText(goods_kind);
//				orderInfo.put("goods_kindname", goods_kindname);
//
//				String goods_packing = orderInfo.getStr("goods_packing");
//				String goods_packingname = DictCache.cache
//						.getDicByText(goods_packing);
//				orderInfo.put("goods_packingname", goods_packingname);
//
//				int goods_status = orderInfo.getInt("goods_status");
//				String goods_statusname = DictCache.cache.getDicByText(
//						String.valueOf(goods_status), "GOODS_STATUS");
//				orderInfo.put("goods_statusname", goods_statusname);
//
//				int goods_spec = orderInfo.getInt("goods_spec");
//				orderInfo.put("goods_spec", goods_spec + "斤");
//
//				BigDecimal sale_price = orderInfo.getBigDecimal("sale_price");
//				orderInfo.put("sale_price", sale_price + "元");
//
//				BigDecimal unit_price = orderInfo.getBigDecimal("unit_price");
//				orderInfo.put("unit_price", unit_price + "元");
//			}
//		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", orderlist);
		map.put("total", paginate.getTotalRow());
		this.renderJson(map);
	}

	/*
	 * 列表显示所有客户信息
	 */
	public void goodsofflist() {
		Integer page = this.getParaToInt("page");
		Integer rows = this.getParaToInt("rows");

		StringBuffer sqlBefore=new StringBuffer("SELECT gi.goods_id,gi.goods_name,gi.app_name,gi.goods_kind,dic.dict_name,gi.goods_spec,");
		sqlBefore.append("(select sale_price from price where goods_id=gi.goods_id order by set_date desc LIMIT 1) as sale_price,");
		sqlBefore.append("(select UNIT_PRICE from price where goods_id=gi.goods_id order by set_date desc LIMIT 1) as unit_price,");
		sqlBefore.append("(select SUM(sale_num) from store where goods_id=gi.goods_id order by set_date desc) as sale_num,");
		sqlBefore.append("(select store_num from store where goods_id=gi.goods_id order by set_date DESC LIMIT 1) as store_num,");
		sqlBefore.append("(select limit_num from store where goods_id=gi.goods_id order by set_date DESC LIMIT 1) as limit_num");
		String sqlAfter="FROM goodsinfo gi inner join dictionary dic on dic.dict_code=gi.goods_kind where gi.GOODS_STATUS=2  ORDER BY GOODS_ID";
		Page<GoodsInfo> paginate = GoodsInfo.me.paginate(page, rows, sqlBefore.toString(),
				sqlAfter);
		List<GoodsInfo> orderlist = paginate.getList();

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", orderlist);
		map.put("total", paginate.getTotalRow());
		this.renderJson(map);
	}

	/*
	 * 待上架商品列表
	 */
	public void readyForPutAwayGoods() {
		Integer page = this.getParaToInt("page");
		Integer rows = this.getParaToInt("rows");
		String sqlBefore = " SELECT g.*  ";
		StringBuffer sqlAfter = new StringBuffer(
				" FROM goodsinfo g where g.goods_status=0 ORDER BY g.create_time DESC ");
		Page<GoodsInfo> paginate = GoodsInfo.me.paginate(page, rows, sqlBefore,
				sqlAfter.toString());
		List<GoodsInfo> orderlist = paginate.getList();
		if (orderlist != null && orderlist.size() > 0) {
			for (GoodsInfo orderInfo : orderlist) {
				String goods_kind = orderInfo.getStr("goods_kind");
				String goods_kindname = DictCache.cache
						.getDicByText(goods_kind);
				orderInfo.put("goods_kindname", goods_kindname);

				String goods_packing = orderInfo.getStr("goods_packing");
				String goods_packingname = DictCache.cache
						.getDicByText(goods_packing);
				orderInfo.put("goods_packingname", goods_packingname);

				Date createtime = orderInfo.getDate("create_time");
				orderInfo.put("create_time",
						CommonUtils.getDateToYMDStr(createtime));

			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", orderlist);
		map.put("total", paginate.getTotalRow());
		this.renderJson(map);
	}

	// 上架或者下架
	public void putAway() {
		String goods_id = this.getPara("goods_id");
		String goods_status = this.getPara("goods_status");
		GoodsInfo goodsInfo = GoodsInfo.me.findById(goods_id);
		goodsInfo.set("goods_status", goods_status);

		if ("1".equals(goods_status)) {

			goodsInfo.set("put_time", DateUtil.getNow());

			Userinfo userinfo = (Userinfo) this.getSessionAttr("LOGIN_USER");
			int userid = userinfo.getInt("USERID");

			Record price = Price.me.getPriceBystation(goods_id, "-1");
			// 上架时同步到所有站点
			List<Station> stationList = Station.dao
					.find(" select * from station ");
			for (Station stat : stationList) {
				int station_id = stat.getInt("station_id");

				Record pric = Price.me.getPriceById(goods_id,
						CommonUtils.getCurrentDate(),
						String.valueOf(station_id));
				if (pric != null) {
					int id = pric.getInt("id");
					Price.me.deleteById(id);
				}

				Price pri = new Price();
				pri.set("set_date", price.getDate("set_date"));
				pri.set("goods_id", goods_id);
				pri.set("sale_price", price.getBigDecimal("sale_price"));
				pri.set("unit_price", price.getBigDecimal("unit_price"));
				pri.set("minus_price", price.getBigDecimal("minus_price"));
				pri.set("update_userid", userid);
				pri.set("update_time", DateUtil.getNow());
				pri.set("station_id", station_id);
				pri.save();
			}
		} else if ("2".equals(goods_status)) {
			goodsInfo.set("off_time", DateUtil.getNow());
		}
		boolean update = false;
		update = goodsInfo.update();
		this.renderText(update ? "1" : "0");
	}
	
	// 已下架的再上架
	public void putAwayoff() {
		String goods_id = this.getPara("goods_id");
		String price_sql="select COUNT(1) FROM price where SET_DATE='"+DateUtil.getToday()+"' AND GOODS_ID="+goods_id;
		String store_sql="select COUNT(1) FROM store where SET_DATE='"+DateUtil.getToday()+"' AND GOODS_ID="+goods_id;
		int pcnts=Db.queryLong(price_sql).intValue();
		int scnts=Db.queryLong(store_sql).intValue();
		if(pcnts==0 || scnts==0){
			this.renderText("0");
			return;
		}
		String goods_status = this.getPara("goods_status");
		GoodsInfo goodsInfo = GoodsInfo.me.findById(goods_id);
		goodsInfo.set("goods_status", goods_status);
		if ("1".equals(goods_status)) {
			goodsInfo.set("put_time", DateUtil.getNow());
		}
		boolean update = false;
		update = goodsInfo.update();
		this.renderText(update ? "1" : "0");
	}

	/**
	 * 进入商品新增页面
	 */
	public void setgoods() {
		this.renderJsp("/admin/system/goodsadd.jsp");
	}

	/***
	 * 下拉列表
	 */
	public void goodskind() {
		String goods = getPara(0);
		List<Dictionary> diclist = DictCache.cache.getDicByDictype(goods);
		this.renderJson(diclist);
	}

	/***
	 * 下拉列表
	 */
	public void station() {
		List<Station> list = Station.dao
				.find("select * from station order by create_time desc ");
		this.renderJson(list);
	}

	/**
	 * 添加新的商品
	 */
	public void addgoods() {
		UploadFile upFile = getFile("img", "goods/");
		// 文件重命名这样用： getFile().getFile().renameTo(new File(newFileNameHere));
		if (upFile != null) {
			String fileName = upFile.getFileName();
			String imgUrl = PropKit.use("config.properties").get("web.url")
					+ "/upload/goods/" + fileName;

			GoodsInfo goods = this.getModel(GoodsInfo.class, "goodsinfo");
			goods.set("goods_status", "0");
			goods.set("create_time", DateUtil.getNow());
			goods.set("status", "0");
			goods.set("img_url", imgUrl);
			boolean add = goods.save();
			// 商品价格
			int goods_id = goods.get("goods_id");

			String sale_price = getPara("price.sale_price");
			String minus = getPara("price.minus_price");
			if (minus == null || "".equals(minus)) {
				minus = "0";
			}
			BigDecimal minus_price = new BigDecimal(minus);
			int count = minus_price.compareTo(BigDecimal.ZERO);
			if (count != 0) {
				sale_price = minus;
			}

			String set_date = getPara("price.set_date");

			Userinfo userinfo = (Userinfo) this.getSessionAttr("LOGIN_USER");
			int userid = userinfo.getInt("USERID");

			Price price = this.getModel(Price.class, "price");
			price.set("set_date", CommonUtils.parseDate(set_date));
			price.set("goods_id", goods_id);
			price.set("update_userid", userid);
			price.set("minus_price", minus_price);
			price.set("update_time", DateUtil.getNow());
			price.set("station_id", "-1");
			price.save();

			Store store = this.getModel(Store.class, "store");
			store.set("set_date", set_date);
			store.set("goods_id", goods_id);
			store.set("update_time", DateUtil.getNow());
			store.set("sale_price", sale_price);
			store.save();

			this.setAttr("addMsg", add ? "商品信息添加成功！" : "商品信息添加失败");
		} else {
			this.setAttr("addMsg", "商品信息添加失败:没上传任何可用的标题图片");

		}
		this.renderJsp("/admin/system/readyForPutAwayGoods.jsp");
	}

	/**
	 * 进入商品新增页面
	 */
	public void goodsview() {
		String goods_id = getPara(0);
		GoodsInfo goodsInfo = GoodsInfo.me.findById(goods_id);
		Record price = Price.me.getPriceById(goods_id);
		Record store = Store.me.getStoreById(goods_id);

		this.setAttr("goodsInfo", goodsInfo);
		this.setAttr("price", price);
		this.setAttr("store", store);
		this.renderJsp("/admin/system/goodsedit.jsp");
	}

	/**
	 * 编辑商品信息
	 */
	public void editgoods() {
		UploadFile upFile = getFile("img", "goods/");
		GoodsInfo goods = this.getModel(GoodsInfo.class, "goodsinfo");
		if (upFile != null) {
			String fileName = upFile.getFileName();
			String imgUrl = PropKit.use("config.properties").get("web.url")
					+ "/upload/goods/" + fileName;
			goods.set("img_url", imgUrl);
		}
		boolean add = goods.update();

		Store store = this.getModel(Store.class, "store");
		store.set("set_date", getPara("price.set_date"));
		store.update();

		Price price = this.getModel(Price.class, "price");
		price.update();

		this.setAttr("addMsg", add ? "商品信息修改成功！" : "商品信息修改失败");
		this.renderJsp("/admin/system/readyForPutAwayGoods.jsp");
	}

	/**
	 * 进入到编辑商品信息的页面（只是针对商品本身的信息）
	 */
	public void editGoodsinfoBefore() {
		String goods_id = getPara(0);
		GoodsInfo goodsInfo = GoodsInfo.me.findById(goods_id);
		this.setAttr("goodsInfo", goodsInfo);
		this.renderJsp("/admin/system/goodsinfoEdit.jsp");
	}

	/**
	 * 修改商品本身的信息
	 */
	public void editGoodsinfo() {
		UploadFile upFile = getFile("img", "goods/");
		try {
			GoodsInfo goods = this.getModel(GoodsInfo.class, "goodsinfo");
			if (upFile != null) {
				String fileName = upFile.getFileName();
				String imgUrl = PropKit.use("config.properties").get("web.url")
						+ "/upload/goods/" + fileName;
				goods.set("img_url", imgUrl);
			}
			goods.set("MODIFY_TIME", DateUtil.getNow());
			boolean add = goods.update();
			this.setAttr("addMsg", add?"商品信息修改成功！":"商品信息修改失败");
			this.setAttr("goodsInfo", goods);
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.renderJsp("/admin/system/goodsinfoEdit.jsp");
	}

	/**
	 * 进入商品新增页面
	 */
	public void fixPrice() {
		this.renderJsp("/admin/system/fixPriceList.jsp");
	}

	/*
	 * 列表显示所有客户信息
	 */
	public void fixPriceList() {
		String station = this.getPara("station");

		StringBuffer sqlAfter = new StringBuffer(
				" SELECT g.*,c.store_num,b.set_date,b.SALE_PRICE,b.UNIT_PRICE,c.sale_num FROM goodsinfo g,PRICE b,store c where g.goods_status=1 and g.GOODS_ID=c.GOODS_ID AND g.GOODS_ID=b.GOODS_ID  ");
		sqlAfter.append(" and date(b.set_date) = curdate() and  date(c.set_date) = curdate() ");
		if (station == null || "".equals(station)) {
			sqlAfter.append(" and b.station_id= -1 ");
		}
		if (station != null && !"".equals(station)) {
			sqlAfter.append(" and b.station_id=" + station);
		}
		sqlAfter.append(" ORDER BY g.create_time DESC ");

		Map<String, Object> map = new HashMap<String, Object>();

		List<GoodsInfo> orderlist = GoodsInfo.me.find(sqlAfter.toString()); // paginate.getList();
		if (orderlist != null && orderlist.size() > 0) {
			goodsSetValue(orderlist);
			map.put("rows", orderlist);
		} else {
			StringBuffer sqlAfter1 = new StringBuffer(
					" SELECT g.*,c.store_num,b.set_date,b.SALE_PRICE,b.UNIT_PRICE,c.sale_num FROM goodsinfo g,PRICE b,store c where g.goods_status=1 and g.GOODS_ID=c.GOODS_ID AND g.GOODS_ID=b.GOODS_ID  ");
			sqlAfter1
					.append(" and date(b.set_date) = curdate() and  date(c.set_date) = curdate() ");
			sqlAfter1.append(" and b.station_id= -1 ");
			sqlAfter1.append(" ORDER BY g.create_time DESC ");

			List<GoodsInfo> orderlist1 = GoodsInfo.me
					.find(sqlAfter1.toString()); // paginate1.getList();
			goodsSetValue(orderlist1);
			map.put("rows", orderlist1);
		}
		this.renderJson(map);
	}

	/**
	 * 进入商品新增页面
	 */
	public void fixPricetoday() {
		this.renderJsp("/admin/system/fixPriceListoday.jsp");
	}

	/*
	 * 列表显示所有菜品价格信息
	 */
	public void fixPriceListoday() {
		String station = this.getPara("station");
		String goodsname = this.getPara("goodsname");

		StringBuffer sqlAfter = new StringBuffer(
				" SELECT g.*,c.store_num,b.set_date,b.SALE_PRICE,b.UNIT_PRICE,c.sale_num FROM goodsinfo g,PRICE b,store c where g.goods_status=1 and g.GOODS_ID=c.GOODS_ID AND g.GOODS_ID=b.GOODS_ID  ");
		sqlAfter.append(" and date(b.set_date) = curdate() and  date(c.set_date) = curdate() ");
		if (station == null || "".equals(station)) {
			sqlAfter.append(" and b.station_id= -1 ");
		}
		if (goodsname != null && !"".equals(goodsname)) {
			sqlAfter.append(" and g.goods_name like '%" + goodsname + "%' ");
		}
		if (station != null && !"".equals(station)) {
			sqlAfter.append(" and b.station_id=" + station);
		}
		sqlAfter.append(" ORDER BY g.goods_id asc ");

		Map<String, Object> map = new HashMap<String, Object>();

		List<GoodsInfo> orderlist = GoodsInfo.me.find(sqlAfter.toString()); // paginate.getList();
		if (orderlist != null && orderlist.size() > 0) {
			goodsSetValue(orderlist);
			map.put("rows", orderlist);
		} else {
			StringBuffer sqlAfter1 = new StringBuffer(
					" SELECT g.*,c.store_num,b.set_date,b.SALE_PRICE,b.UNIT_PRICE,c.sale_num FROM goodsinfo g,PRICE b,store c where g.goods_status=1 and g.GOODS_ID=c.GOODS_ID AND g.GOODS_ID=b.GOODS_ID  ");
			sqlAfter1
					.append(" and date(b.set_date) = curdate() and  date(c.set_date) = curdate() ");
			sqlAfter1.append(" and b.station_id= -1 ");
			sqlAfter1.append(" ORDER BY g.goods_id asc ");

			List<GoodsInfo> orderlist1 = GoodsInfo.me
					.find(sqlAfter1.toString()); // paginate1.getList();
			goodsSetValue(orderlist1);
			map.put("rows", orderlist1);
		}
		this.renderJson(map);
	}

	/*
	 * 批量设置定价
	 */
	@SuppressWarnings("unchecked")
	public void batchSavePricetoday() throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(
				(ServletInputStream) this.getRequest().getInputStream()));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		Userinfo userinfo = (Userinfo) this.getSessionAttr("LOGIN_USER");
		int userid = userinfo.getInt("USERID");

		List<Map<String, Object>> pricelist = JsonUtil.getList4Json(
				sb.toString(), Map.class);
		for (Map<String, Object> dataMap : pricelist) {
			String goods_id = CommonUtils.getMapKeyVal(dataMap, "goods_id");
			String slsale = CommonUtils.getMapKeyVal(dataMap, "slsale");
			String weight = CommonUtils.getMapKeyVal(dataMap, "slunit");
			BigDecimal slunit = CommonUtils.count(slsale, weight);

			String station_id = CommonUtils.getMapKeyVal(dataMap, "station_id");
			String stationProperty = CommonUtils.getMapKeyVal(dataMap,
					"stationProperty");
			if (stationProperty != null && !"".equals(stationProperty)
					&& !"-1".equals(stationProperty)) {
				List<Record> stationList = Station.dao
						.getStationList(stationProperty);
				if (stationList != null && stationList.size() > 0) {
					for (Record rds : stationList) {
						int stationid = rds.getInt("station_id");
						// 当天后一天的日期
						String curdate = CommonUtils.getCurrentDate();
						Record rd = Price.me.getPriceById(goods_id, curdate,
								String.valueOf(stationid));
						if (rd != null) {
							int id = rd.getInt("id");
							Price price = new Price();
							price.set("id", id);
							price.set("set_date", curdate);
							price.set("goods_id", goods_id);
							price.set("sale_price", slsale);
							price.set("unit_price", slunit);
							price.set("update_userid", userid);
							price.set("update_time", CommonUtils.getDate());
							price.set("station_id", stationid);
							price.update();
						} else {
							Price price = new Price();
							price.set("set_date", curdate);
							price.set("goods_id", goods_id);
							price.set("sale_price", slsale);
							price.set("unit_price", slunit);
							price.set("minus_price", 0);
							price.set("update_userid", userid);
							price.set("update_time", CommonUtils.getDate());
							price.set("station_id", stationid);
							price.save();
						}
					}
				}
			} else {
				// 当天后一天的日期
				String curdate = CommonUtils.getCurrentDate();
				Record rd = Price.me
						.getPriceById(goods_id, curdate, station_id);
				if (rd != null) {
					int id = rd.getInt("id");
					Price price = new Price();
					price.set("id", id);
					price.set("set_date", curdate);
					price.set("goods_id", goods_id);
					price.set("sale_price", slsale);
					price.set("unit_price", slunit);
					price.set("update_userid", userid);
					price.set("update_time", CommonUtils.getDate());
					price.set("station_id", station_id);
					price.update();
				} else {
					Price price = new Price();
					price.set("set_date", curdate);
					price.set("goods_id", goods_id);
					price.set("sale_price", slsale);
					price.set("unit_price", slunit);
					price.set("minus_price", 0);
					price.set("update_userid", userid);
					price.set("update_time", CommonUtils.getDate());
					price.set("station_id", station_id);
					price.save();
				}
			}
		}
		this.renderJson("0");
	}

	/**
	 * 进入商品次日定价
	 */
	public void fixPricenextoday() {
		this.renderJsp("/admin/system/fixPriceListnextoday.jsp");
	}

	/*
	 * 列表显示所有商品次日定价信息
	 */
	public void fixPriceListnextoday() {
		String station = this.getPara("station");
		String goodsname = this.getPara("goodsname");

		StringBuffer sqlAfter = new StringBuffer(
				" SELECT g.*,c.store_num,b.set_date,b.SALE_PRICE,b.UNIT_PRICE,c.sale_num FROM goodsinfo g,PRICE b,store c where g.goods_status=1 and g.GOODS_ID=c.GOODS_ID AND g.GOODS_ID=b.GOODS_ID  ");
		sqlAfter.append(" and date(b.set_date) = curdate() and  date(c.set_date) = curdate() ");
		if (station == null || "".equals(station)) {
			sqlAfter.append(" and b.station_id= -1 ");
		}
		if (goodsname != null && !"".equals(goodsname)) {
			sqlAfter.append(" and g.goods_name like '%" + goodsname + "%' ");
		}
		if (station != null && !"".equals(station)) {
			sqlAfter.append(" and b.station_id=" + station);
		}
		sqlAfter.append(" ORDER BY g.goods_id ");

		Map<String, Object> map = new HashMap<String, Object>();

		List<GoodsInfo> orderlist = GoodsInfo.me.find(sqlAfter.toString()); // paginate.getList();
		if (orderlist != null && orderlist.size() > 0) {
			List<Price> priceList=GoodsInfo.me.findLatestPriceList(station, goodsname);
			goodsSetValue(orderlist,priceList);
			map.put("rows", orderlist);
		} else {
			StringBuffer sqlAfter1 = new StringBuffer(
					" SELECT g.*,c.store_num,b.set_date,b.SALE_PRICE,b.UNIT_PRICE,c.sale_num FROM goodsinfo g,PRICE b,store c where g.goods_status=1 and g.GOODS_ID=c.GOODS_ID AND g.GOODS_ID=b.GOODS_ID  ");
			sqlAfter1
					.append(" and date(b.set_date) = curdate() and  date(c.set_date) = curdate() ");
			sqlAfter1.append(" and b.station_id= -1 ");
			sqlAfter1.append("  ORDER BY g.goods_id ");

			List<GoodsInfo> orderlist1 = GoodsInfo.me
					.find(sqlAfter1.toString()); // paginate1.getList();
			goodsSetValue(orderlist1);
			map.put("rows", orderlist1);
		}
		this.renderJson(map);
	}

	/*
	 * 批量设置定价
	 */
	@SuppressWarnings("unchecked")
	public void batchSavePricenextoday() throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(
				(ServletInputStream) this.getRequest().getInputStream()));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		Userinfo userinfo = (Userinfo) this.getSessionAttr("LOGIN_USER");
		int userid = userinfo.getInt("USERID");

		List<Map<String, Object>> pricelist = JsonUtil.getList4Json(
				sb.toString(), Map.class);
		for (Map<String, Object> dataMap : pricelist) {
			String goods_id = CommonUtils.getMapKeyVal(dataMap, "goods_id");
			String slsale = CommonUtils.getMapKeyVal(dataMap, "slsale");

			String weight = CommonUtils.getMapKeyVal(dataMap, "slunit");
			BigDecimal slunit = CommonUtils.count(slsale, weight);

			String station_id = CommonUtils.getMapKeyVal(dataMap, "station_id");
			String stationProperty = CommonUtils.getMapKeyVal(dataMap,
					"stationProperty");
			if (stationProperty != null && !"".equals(stationProperty)
					&& !"-1".equals(stationProperty)) {
				List<Record> stationList = Station.dao
						.getStationList(stationProperty);
				if (stationList != null && stationList.size() > 0) {
					for (Record rds : stationList) {
						int stationid = rds.getInt("station_id");
						String curdate = CommonUtils
								.getSpecifiedDayAfter(CommonUtils
										.getCurrentDate());
						Record rd = Price.me.getPriceById(goods_id, curdate,
								String.valueOf(stationid));
						if (rd != null) {
							int id = rd.getInt("id");
							Price.me.deleteById(id);
						}
						Price price = new Price();
						price.set("set_date", curdate);
						price.set("goods_id", goods_id);
						price.set("sale_price", slsale);
						price.set("unit_price", slunit);
						price.set("minus_price", 0);
						price.set("update_userid", userid);
						price.set("update_time", CommonUtils.getDate());
						price.set("station_id", stationid);
						price.save();
					}
				}
			} else {
				// 当天后一天的日期
				String curdate = CommonUtils.getSpecifiedDayAfter(CommonUtils
						.getCurrentDate());
				Record rd = Price.me
						.getPriceById(goods_id, curdate, station_id);
				if (rd != null) {
					int id = rd.getInt("id");
					Price.me.deleteById(id);
				}
				Price price = new Price();
				price.set("set_date", curdate);
				price.set("goods_id", goods_id);
				price.set("sale_price", slsale);
				price.set("unit_price", slunit);
				price.set("minus_price", 0);
				price.set("update_userid", userid);
				price.set("update_time", CommonUtils.getDate());
				price.set("station_id", station_id);
				price.save();

			}
		}
		this.renderJson("0");
	}

	/****
	 * 变量转换
	 * 
	 * @param orderlist
	 */
	private void goodsSetValue(List<GoodsInfo> orderlist) {
		for (GoodsInfo orderInfo : orderlist) {
			String goods_kind = orderInfo.getStr("goods_kind");
			String goods_kindname = DictCache.cache.getDicByText(goods_kind);
			orderInfo.put("goods_kindname", goods_kindname);

			String goods_packing = orderInfo.getStr("goods_packing");
			String goods_packingname = DictCache.cache
					.getDicByText(goods_packing);
			orderInfo.put("goods_packingname", goods_packingname);

			int goods_status = orderInfo.getInt("goods_status");
			String goods_statusname = DictCache.cache.getDicByText(
					String.valueOf(goods_status), "GOODS_STATUS");
			orderInfo.put("goods_statusname", goods_statusname);

			int goods_spec = orderInfo.getInt("goods_spec");
			orderInfo.put("goods_spec", goods_spec);
		
		}
	}
	
	private void goodsSetValue(List<GoodsInfo> orderlist,List<Price> priceList) {
		for (GoodsInfo orderInfo : orderlist) {
			String goods_kind = orderInfo.getStr("goods_kind");
			String goods_kindname = DictCache.cache.getDicByText(goods_kind);
			orderInfo.put("goods_kindname", goods_kindname);

			String goods_packing = orderInfo.getStr("goods_packing");
			String goods_packingname = DictCache.cache
					.getDicByText(goods_packing);
			orderInfo.put("goods_packingname", goods_packingname);

			int goods_status = orderInfo.getInt("goods_status");
			String goods_statusname = DictCache.cache.getDicByText(
					String.valueOf(goods_status), "GOODS_STATUS");
			orderInfo.put("goods_statusname", goods_statusname);

			int goods_spec = orderInfo.getInt("goods_spec");
			orderInfo.put("goods_spec", goods_spec);
			
			Price price=GoodsInfo.me.findLatestPriceByGoodsid(orderInfo.getInt("goods_id"), priceList);
			if(price!=null){
				orderInfo.put("sale_price0",price.getBigDecimal("SALE_PRICE"));
			}else{
				orderInfo.put("sale_price0",orderInfo.getBigDecimal("sale_price"));
			}
		}
	}

	/*
	 * 批量设置定价
	 */
	@SuppressWarnings("unchecked")
	public void batchSavePrice() throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(
				(ServletInputStream) this.getRequest().getInputStream()));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		Userinfo userinfo = (Userinfo) this.getSessionAttr("LOGIN_USER");
		int userid = userinfo.getInt("USERID");

		List<Map<String, Object>> pricelist = JsonUtil.getList4Json(
				sb.toString(), Map.class);
		for (Map<String, Object> dataMap : pricelist) {
			String goods_id = CommonUtils.getMapKeyVal(dataMap, "goods_id");
			String slsale = CommonUtils.getMapKeyVal(dataMap, "slsale");

			String weight = CommonUtils.getMapKeyVal(dataMap, "slunit");
			BigDecimal slunit = CommonUtils.count(slsale, weight);

			String station_id = CommonUtils.getMapKeyVal(dataMap, "station_id");
			// 当天后一天的日期
			String curdate = CommonUtils.getSpecifiedDayAfter(CommonUtils
					.getCurrentDate());
			Record rd = Price.me.getPriceById(goods_id, curdate, station_id);
			if (rd != null) {
				int id = rd.getInt("id");
				Price.me.deleteById(id);
			}
			Price price = new Price();
			price.set("set_date", curdate);
			price.set("goods_id", goods_id);
			price.set("sale_price", slsale);
			price.set("unit_price", slunit);
			price.set("minus_price", 0);
			price.set("update_userid", userid);
			price.set("update_time", CommonUtils.getDate());
			price.set("station_id", station_id);
			price.save();
		}
		this.renderJson("0");
	}

	/**
	 * 进入商品新增页面
	 */
	public void fixStore() {
		this.renderJsp("/admin/system/fixStoreList.jsp");
	}

	/*
	 * 列表显示所有客户信息
	 */
	public void fixStoreList() {
		Integer page = this.getParaToInt("page");
		Integer rows = this.getParaToInt("rows");
		String sqlBefore = " SELECT g.*,c.store_num,c.set_date,c.sale_num,c.limit_num  ";
		StringBuffer sqlAfter = new StringBuffer(
				" FROM goodsinfo g,store c where g.goods_status=1 and g.GOODS_ID=c.GOODS_ID  ");
		sqlAfter.append("  and  date(c.set_date) = curdate() ");
		sqlAfter.append(" ORDER BY g.GOODS_ID ");

		Page<GoodsInfo> paginate = GoodsInfo.me.paginate(page, rows, sqlBefore,
				sqlAfter.toString());
		List<GoodsInfo> orderlist = paginate.getList();
		if (orderlist != null && orderlist.size() > 0) {
			List<Store> storeList=GoodsInfo.me.findLatestStoreList();//
			for (GoodsInfo orderInfo : orderlist) {
				String goods_kind = orderInfo.getStr("goods_kind");
				String goods_kindname = DictCache.cache
						.getDicByText(goods_kind);
				orderInfo.put("goods_kindname", goods_kindname);

				String goods_packing = orderInfo.getStr("goods_packing");
				String goods_packingname = DictCache.cache
						.getDicByText(goods_packing);
				orderInfo.put("goods_packingname", goods_packingname);

				int goods_status = orderInfo.getInt("goods_status");
				String goods_statusname = DictCache.cache.getDicByText(
						String.valueOf(goods_status), "GOODS_STATUS");
				orderInfo.put("goods_statusname", goods_statusname);

				int goods_spec = orderInfo.getInt("goods_spec");
				orderInfo.put("goods_spec", goods_spec + "斤");
				
				Store store=GoodsInfo.me.findLatestStoreByGoodsid(orderInfo.getInt("GOODS_ID"), storeList);
				try {
					if(store!=null){
						orderInfo.put("store_num0", store.getInt("STORE_NUM"));
						orderInfo.put("limit_num0", store.getInt("LIMIT_NUM"));
					}else{
						orderInfo.put("store_num0", orderInfo.getInt("STORE_NUM"));
						orderInfo.put("limit_num0", orderInfo.getInt("LIMIT_NUM"));
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", orderlist);
		map.put("total", paginate.getTotalRow());
		this.renderJson(map);
	}

	/*
	 * 批量设置定价
	 */
	@SuppressWarnings("unchecked")
	public void batchSaveStore() throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(
				(ServletInputStream) this.getRequest().getInputStream()));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}

		Userinfo userinfo = (Userinfo) this.getSessionAttr("LOGIN_USER");
		int userid = userinfo.getInt("USERID");

		List<Map<String, Object>> pricelist = JsonUtil.getList4Json(
				sb.toString(), Map.class);
		for (Map<String, Object> dataMap : pricelist) {
			String goods_id = CommonUtils.getMapKeyVal(dataMap, "goods_id");
			String slstore = CommonUtils.getMapKeyVal(dataMap, "slstore");
			String slimit = CommonUtils.getMapKeyVal(dataMap, "slimit");
			// 当天后一天的日期
			String curdate = CommonUtils.getSpecifiedDayAfter(CommonUtils
					.getCurrentDate());
			Record rd = Store.me.getStoreById(goods_id, curdate);
			if (rd != null) {
				int store_id = rd.getInt("store_id");
				Store.me.deleteById(store_id);
			}
			Record rds = Store.me.getStoreById(goods_id);
			Store store = new Store();
			store.set("set_date", curdate);
			store.set("goods_id", goods_id);
			store.set("store_num", slstore);
			store.set("sale_num", "0");
			store.set("sale_price", rds.getBigDecimal("sale_price"));
			store.set("limit_num", slimit);
			store.set("update_userid", userid);
			store.set("update_time", CommonUtils.getDate());
			store.save();
		}
		this.renderJson("0");
	}

	/**
	 * 进入商品新增页面
	 */
	public void fixStoretoday() {
		this.renderJsp("/admin/system/fixStoreListoday.jsp");
	}

	/*
	 * 列表显示所有客户信息
	 */
	public void fixStoreListoday() {
		Integer page = this.getParaToInt("page");
		Integer rows = this.getParaToInt("rows");
		String sqlBefore = " SELECT g.*,c.store_num,c.set_date,c.sale_num,c.limit_num  ";
		StringBuffer sqlAfter = new StringBuffer(
				" FROM goodsinfo g,store c where g.goods_status=1 and g.GOODS_ID=c.GOODS_ID  ");
		sqlAfter.append("  and  date(c.set_date) = curdate() ");
		sqlAfter.append(" ORDER BY g.goods_id ");

		Page<GoodsInfo> paginate = GoodsInfo.me.paginate(page, rows, sqlBefore,
				sqlAfter.toString());
		List<GoodsInfo> orderlist = paginate.getList();
		if (orderlist != null && orderlist.size() > 0) {
			for (GoodsInfo orderInfo : orderlist) {
				String goods_kind = orderInfo.getStr("goods_kind");
				String goods_kindname = DictCache.cache
						.getDicByText(goods_kind);
				orderInfo.put("goods_kindname", goods_kindname);

				String goods_packing = orderInfo.getStr("goods_packing");
				String goods_packingname = DictCache.cache
						.getDicByText(goods_packing);
				orderInfo.put("goods_packingname", goods_packingname);

				int goods_status = orderInfo.getInt("goods_status");
				String goods_statusname = DictCache.cache.getDicByText(
						String.valueOf(goods_status), "GOODS_STATUS");
				orderInfo.put("goods_statusname", goods_statusname);

				int goods_spec = orderInfo.getInt("goods_spec");
				orderInfo.put("goods_spec", goods_spec + "斤");

			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", orderlist);
		map.put("total", paginate.getTotalRow());
		this.renderJson(map);
	}

	/*
	 * 批量设置定价
	 */
	@SuppressWarnings("unchecked")
	@Before(Tx.class)
	public void batchSaveStoretoday() throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(
				(ServletInputStream) this.getRequest().getInputStream()));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}

		Userinfo userinfo = (Userinfo) this.getSessionAttr("LOGIN_USER");
		int userid = userinfo.getInt("USERID");

		List<Map<String, Object>> pricelist = JsonUtil.getList4Json(
				sb.toString(), Map.class);
		for (Map<String, Object> dataMap : pricelist) {
			String goods_id = CommonUtils.getMapKeyVal(dataMap, "goods_id");
			String slstore = CommonUtils.getMapKeyVal(dataMap, "slstore");
			String slimit = CommonUtils.getMapKeyVal(dataMap, "slimit");
			// 当天后一天的日期
			String curdate = CommonUtils.getCurrentDate();
			Record rd = Store.me.getStoreById(goods_id, curdate);
			if (rd != null) {
				int store_id = rd.getInt("store_id");
				Store store = new Store();
				store.set("store_id", store_id);
				store.set("set_date", curdate);
				store.set("goods_id", goods_id);
				store.set("store_num", slstore);
				store.set("limit_num", slimit);
				store.set("update_userid", userid);
				store.set("update_time", CommonUtils.getDate());
				store.update();
			} else {
				Record rds = Store.me.getStoreById(goods_id);
				Store store = new Store();
				store.set("set_date", curdate);
				store.set("goods_id", goods_id);
				store.set("store_num", slstore);
				store.set("sale_num", "0");
				store.set("sale_price", rds.getBigDecimal("sale_price"));
				store.set("limit_num", slimit);
				store.set("update_userid", userid);
				store.set("update_time", CommonUtils.getDate());
				store.save();
			}
		}
		this.renderJson("0");
	}

	/**
	 * 进入商品新增页面
	 */
	public void storepriceview() {
		String goods_id = getPara(0);
		Integer method=this.getParaToInt(1);
		GoodsInfo goodsInfo = GoodsInfo.me.findById(goods_id);
		Record price = Price.me.getPriceById(goods_id);
		Record store = Store.me.getStoreById(goods_id);

		this.setAttr("goodsInfo", goodsInfo);
		this.setAttr("price", price);
		this.setAttr("store", store);
		this.setAttr("method", method);
		this.renderJsp("/admin/system/storepriceedit.jsp");
	}

	/**
	 * 编辑库存价格信息
	 */
	public void editstoreprice() {
		Object user=this.getSessionAttr("LOGIN_USER");
		if(user==null){
			this.redirect("/login.jsp");
			return;
		}
		Integer userid=((Userinfo)user).getInt("USERID");
		Store store = this.getModel(Store.class, "store");
		Price price = this.getModel(Price.class, "price");
		int goods_id=price.getInt("goods_id");
		double sale_price=price.getBigDecimal("sale_price").doubleValue();
		int store_num=store.getInt("store_num");
		int limit_num=store.getInt("limit_num");
		Integer method=this.getParaToInt("method");
		GoodsInfo goodsinfo=GoodsInfo.me.findById(goods_id);
		int goods_spec=goodsinfo.getInt("GOODS_SPEC");
		String unit_price=new java.text.DecimalFormat("#.00").format(sale_price/goods_spec);
		List<String> sqlList=new ArrayList<String>();
		StringBuffer sql=new StringBuffer("DELETE FROM price where SET_DATE='"+DateUtil.getToday()+"' AND GOODS_ID="+goods_id);
		sqlList.add(sql.toString());
		
		sql=new StringBuffer("insert into price(SET_DATE,GOODS_ID,SALE_PRICE,UNIT_PRICE,MINUS_PRICE,UPDATE_USERID,UPDATE_TIME,STATION_ID)");
		sql.append(" select '"+DateUtil.getToday()+"',"+goods_id+","+sale_price+","+unit_price+",0,"+userid+",'"+DateUtil.getNow()+"',-1");
		sqlList.add(sql.toString());
		
		sql=new StringBuffer("insert into price(SET_DATE,GOODS_ID,SALE_PRICE,UNIT_PRICE,MINUS_PRICE,UPDATE_USERID,UPDATE_TIME,STATION_ID)");
		sql.append(" select '"+DateUtil.getToday()+"',"+goods_id+","+sale_price+","+unit_price+",0,"+userid+",'"+DateUtil.getNow()+"',STATION_ID from station");
		sqlList.add(sql.toString());
		
		sql=new StringBuffer("DELETE FROM store where SET_DATE='"+DateUtil.getToday()+"' AND GOODS_ID="+goods_id);
		sqlList.add(sql.toString());
		
		sql=new StringBuffer("insert into store(set_date,goods_id,store_num,sale_num,sale_price,LIMIT_num,update_userid,update_time)");
		sql.append(" values('"+DateUtil.getToday()+"',"+goods_id+","+store_num+",0,"+sale_price+","+limit_num+","+userid+",'"+DateUtil.getNow()+"')");
		sqlList.add(sql.toString());
//		boolean add = store.update();	
//		price.update();
		System.out.println();
		boolean add=false;
		try {
			add = DbUtil.batch(sqlList);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		this.setAttr("addMsg", add ? "编辑库存价格信息成功！" : "编辑库存价格信息失败");
	//	this.renderJsp("/admin/system/salegoodslist.jsp");
		if(method!=null && method.intValue()==2){
			this.renderJsp("/admin/system/salegoodsoff.jsp");	
		}else{
			this.renderJsp("/admin/system/salegoodslist.jsp");
		}
		
	}

	public void getGoodsInfolistview() {
		this.renderJsp("/admin/system/rptsalegoods.jsp");
	}

	/**
	 * 查询订单报表数据
	 */
	public void getGoodsInfolist() {
		String station = this.getPara("station");
		String starttime = this.getPara("start_time");
		String endtime = this.getPara("end_time");
		List<Record> rdList = GoodsInfo.me.getGoodsInfolist(station, starttime,
				endtime);
		List<Record> footerList=new ArrayList<Record>();
		int salenum=0;
		int saleweight=0;
		int storenum=0;
		double totalamount=0;
		double minusamount=0;
		double actualamount=0;
		Record rec=new Record();
		String goods_packings="合计";
		if (rdList != null && rdList.size() > 0) {
			for (Record orderInfo : rdList) {
				String goods_kind = orderInfo.getStr("goods_kind");
				String goods_kindname = DictCache.cache
						.getDicByText(goods_kind);
				orderInfo.set("goods_kind", goods_kindname);

				String goods_packing = orderInfo.getStr("goods_packing");
				String goods_packingname = DictCache.cache
						.getDicByText(goods_packing);
				orderInfo.set("goods_packing", goods_packingname);
				try {
					salenum=orderInfo.getBigDecimal("sale_num").intValue()+salenum;
					saleweight=orderInfo.getBigDecimal("weight").intValue()+saleweight;
					storenum=orderInfo.getLong("store_num").intValue()+storenum;
					totalamount=orderInfo.getBigDecimal("original_price").doubleValue()+totalamount;
					minusamount=orderInfo.getBigDecimal("un_price").doubleValue()+minusamount;
					actualamount=orderInfo.getBigDecimal("sale_price").doubleValue()+actualamount;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		rec.set("goods_packing", goods_packings);
		rec.set("sale_num", salenum);
		rec.set("weight", saleweight);
		rec.set("store_num", storenum);
		rec.set("original_price", totalamount);
		rec.set("un_price", minusamount);
		rec.set("sale_price",actualamount);
		footerList.add(rec);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", rdList);
		map.put("footer", footerList);
		this.renderJson(map);
	}
	
	/**
	 * 查找第二天的全站通用价格是否定价
	 */
	public void getNextDayPriceConfirm(){
		int cnt=Price.me.findNextDayPrice();
		this.renderText(cnt>0?"1":"0");
	}
}
